<?php
/**
 * @author spenceryg
 * @date 2022/4/18
 * @time 2:31 下午
 * @focus love & life
 */


namespace app\common\lib\mysql;


use think\facade\Db;

class TableParse
{
    protected $columns = [];

    /**
     * Mysql constructor.
     * @param string $table_name
     * @param string $table_schema
     */
    public function __construct(string $table_name, string $table_schema = '')
    {
        $table_schema = $table_schema ?: env('database_database');
        $sql = "SELECT COLUMN_NAME AS `name`,
                        DATA_TYPE AS `type`,
                        CHARACTER_MAXIMUM_LENGTH AS `length`,
                        NUMERIC_PRECISION AS `precision`,
                        NUMERIC_SCALE AS `scale`,
                        IS_NULLABLE AS `is_null`,
                        CASE WHEN EXTRA = 'auto_increment' THEN 1 ELSE 0 END AS `id_auto_increment`,
                        COLUMN_DEFAULT AS `default`,
                        COLUMN_COMMENT AS `comment`
                        FROM information_schema.COLUMNS
                        WHERE TABLE_SCHEMA='". $table_schema ."' AND TABLE_NAME='". $table_name ."';";
        try {
            $data =  Db::query($sql);
            foreach ($data as $k=>$v){
                $length =  $v['scale'] ? $v['precision']  . ',' . $v['scale'] : '';
                $length = $length ?: ($v['precision'] ?: '');
                $length = $length ?: ($v['length'] ?: '');
                $data[$k]['real_length'] = $length;
            }
            $this->columns = $data;
        } catch (\Exception $e) {
            $this->columns = [];
        }
    }

    public static function getTables()
    {
        $sql = 'show tables;';
        try {
            $tables =  Db::query($sql);
            $res = [];
            foreach ($tables as $table) {
                foreach ($table as $key=>$table_name) {
                    $res[] = $table_name;
                }
            }
            return $res;
        } catch (\Exception $e) {
            return [];
        }

    }

    /**
     * getColumns
     * @return array
     */
    public function getColumns(): array
    {
        return $this->columns;
    }
}
